<template>
  <div class='box-wrap-total'>
    <section class='box-operation'>
      <div class="box-search">
        <div class='form-group-enquire'><Input v-model.trim="searchData.name" placeholder="业务类型" clearable @on-enter="onSearchGetList()"></Input></div>
        <div class='form-group-enquire'>
          <el-select v-model="searchData.sieve_source_config_id" placeholder="请选择筛料源" clearable filterable>
            <el-option :value= row.id v-for="row in statuslist" :label="row.name" :key= row.id >{{row.name}}</el-option>
          </el-select>
        </div>

        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <div class='form-group-addimg' @click='editInfo({},5)'><img src="../../assets/images/peach-svg/add.svg"></div>
        <div class='form-group-addimg6' @click='editInfo({},1)'><img src="../../assets/images/peach-svg/mach.svg"></div>
        <div class='form-group-addimg2' @click='downloadFile(1,{})'><img src="../../assets/images/peach-svg/export.svg"></div>
      </div>
    </section>
    <LibVxeTable class="staticData" :stripe="stripe"  border="none"
    :tableColumns="tableColumns" :tableData="list"
    :slotHeader="slotHeader"
    :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"
    @onPageChange="onChangePageSize"
    @onSelectChange="onCheckChange"
    resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import {ACDN} from '../../commons/staticName'
import { BigNumber } from 'bignumber.js'
export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    const validateunit_p = (rule, value, callback) =>{
      if(value == "" || value == undefined){
        callback(new Error("单价不能为空"));
      }else if(value <=0 ){
        callback(new Error("单价不能小于0"));
      }else if(value < 0.0001 || value > 1){
        callback(new Error("单价不合理，请重新设置单价（单价范围：0.0001元 - 1元）"));
      }else {
        callback();
      }
    };
    return {
      statuslist: [],
      stripe:false,
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        creator_name:"",
        name:"",
        page_index:1,
        page_size:30,
        sieve_source_config_id:''
      },
      sieve_source_config_id:"",
      mnoList:{},
      provinceList:{},
      list:[],
      totalCnt:0,
      info:{},
      formPopIndex:0,
      roles:[],
      leaders:[],
      roleObj:{},
      CountryList:[],
      leaderlist:[],
      footerMethod:{},
      Types:[],
      idlistObj:{},
      nameobj:[],
      selectRows :[],
      SailiaoObj:{},
      tableColumns:[
        {
        field: "Id",
        type:"checkbox",
        align: "center",
        width:50,
        },
        {
          title: "序号",
          // field: "id",
          align: 'center',
          slots:{
            default:({rowIndex},h)=>{
              return [h("span",rowIndex+1)]
            }
          }
        },
        {
          title: "业务类型",
          field: "name",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.name==''||row.name==undefined) {
                    return [h("span","--")]
                }else{
                    return row.name
                }
            }
          }
        },
         {
          title: "筛源名称",
          field: "sieve_source_name",
          align: "center",
          slots: {
            default: ({ row }, h) => {
              if (row.sieve_source_name == "" || row.sieve_source_name == undefined) {
                return [h("span", "--")];
              } else {
                let name = row.sieve_source_name=="internal"?"自研":"数据吧"
                return name+"("+row.sieve_source_alias+")";
              }
            },
          },
        },
        {
          title: "业务类型名称",
          field: "desc",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.desc==''||row.name==undefined) {
                    return [h("span","--")]
                }else{
                    return row.desc
                }
            }
          }
        },
        {
          title: "单价",
          field: "unit_price",
          align: 'center',
          slots:{
            default:({row},h)=>{
                if (row.unit_price==''||row.unit_price==undefined) {
                    return [h("span","--")]
                }else{
                    return row.unit_price / 10000
                }
            }
          }
        },
        {
          title: "状态",
          field: "status",
          align: 'center',
          slots: {
                default: ({row},h) => {
                    let disabled = false;
                    if(this.Perm.add){
                        disabled = false;
                    }
                    return [h("iSwitch",
                            {
                                props: {
                                value:(1 & row.status)==1?true:false,
                                disabled:disabled,
                                size:"large",
                                },
                                on: {
                                'on-change': (value) => {
                                    let info = {"id":row.id};
                                    value==true?this.handleType = 3:this.handleType = 4;
                                    this.updateInfo(info);
                                }
                                }
                            },
                            [
                                h('span', {
                                slot: 'open',
                                domProps: {
                                    innerHTML: '启用'
                                }
                                }),
                                h('span', {
                                slot: 'close',
                                domProps: {
                                    innerHTML: '禁用'
                                }
                                })
                            ]
                    )];
                }
            }
        },
         {
          title: "最后修改时间",
          field: "updated_at",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.updated_at==0){
                return [h("div",'-')]
              }else
              return [h("div",utils.dateFormat(row.updated_at,"yyyy-MM-dd HH:mm:ss"))]
            }
          }
        },
        {
          title: "创建人",
          field: "creator_name",
          align: "center"
        },
        {
          title: "操作",
          field: "action",
          width: 150,
          align: "center",
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];
                hButton.push(h(
                    "div",
                    {
                      class:"two",
                      on: {
                        click: () => {
                          this.editInfo(row,2);
                        }
                      }
                    },
                  ));
                  hButton.push(
                  h(
                    "div",
                    {
                      props: { type: "danger", size: "small" },
                      style: { marginRight: "5px" },
                      class:"three",
                      on: {
                        click: () => {
                          this.sureDel(row,-1);
                        }
                      }
                    },
                  )
                );
              return hButton;
            });
            }
          }
        }
      ],
      format: {
        name:{
          labelName: "业务类型",
          labelType: "select",
          placeholder:"请输入业务类型",
          labelValue:[],
        },
        desc:{
          labelName: "业务类型描述",
          labelType: "text",
          placeholder:"请输入业务类型描述",
        },
        unit_price:{
          labelName: "单价",
          labelType: "text",
          placeholder:"请输入单价"
        },
        sieve_source_config_id:{
          labelName: "筛料源",
          labelType: "select",
          placeholder:"请输入筛料源",
          labelValue:[],
        },
      },
      ruleValidate: {
        name: [{ required: true,message: "业务类型不能为空", trigger: "blur" }],
        unit_price:[{ required: true,validator:validateunit_p, trigger: "blur" }],
      },
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        await this.getList();
        await this.queryTypes();
      }

    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      let res = await this.RequestPost("query_list",this.searchData);
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null)
        this.list = res.data.list;
        this.totalCnt = res.data.total
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },
    //多选框数组
    onCheckChange(rows){  
        this.selectRows = [];
        this.selectRows = rows;
    },
    async queryTypes(){
      let res = await this.RequestPost("queryTypes_list");
      let res2 = await Request.post("customer/sieveConfig","query_list")//筛料源接口
      let label=''
      if(res2.code==0 && res2.data.length != 0){
        res2.data.list.forEach(res2 =>{
          this.$set(this.SailiaoObj,res2.label,res2.id)
          label=res2.name=="sjb"?"数据吧":res2.name=='internal'?'自研':res2.name
          this.statuslist.push({id:res2.id,name:label+"("+res2.alias+")"})
        })
        this.format.sieve_source_config_id.labelValue=this.statuslist
      }
      // let data = res.data

      // let data = res.data.filter((value, index, self) => {
      //   return self.indexOf(value) === index;
      // });
      //去重
      const data = res.data.reduce((accumulator, currentValue) => {
        if (!accumulator.some(item => item.name === currentValue.name)) {
          accumulator.push(currentValue);
        }
        return accumulator;
      }, []);

       if(res.code==0 && data.length != 0){
        data.forEach(res =>{
          this.$set(this.idlistObj,res.name,res.desc)
          this.format.name.labelValue.push({id:res.name,name:res.name})
        })
      }


    },
    //添加 编辑用户
    async editInfo(row,type) {
      // let res3 = await Request.post("customer/sieveConfig","query_list",{default:1})//筛料源接口
      // if(res3.code==0 && res3.data.list!=null){
      //   this.sieve_source_config_id=res3.data.list[0].id
      // }
      let title = "";
      let info = {};
      this.handleType = type
      if(type==1){
        title = "批量修改筛料源";
        let new_ids=""
        if((this.selectRows.checked==true && this.selectRows.records.length>= 1)||(this.selectRows.checked==false && this.selectRows.records.length>= 1)){
          //导出值用id|id形式拼接
          this.selectRows.records.forEach(item => {
            new_ids+='|'+item.id
          });
          if(new_ids!=''){
            new_ids=new_ids.substring(1)
          }
         }
         info = {
            ids:new_ids,
            sieve_source_config_id:""
          };
      }else if(type==2){
        this.format.name.labelDisabled = true
        title = "修改系统价格"
        info = {
          id:row.id,
          name:row.name,
          desc:row.desc,
          unit_price:row.unit_price/10000,
          sieve_source_config_id:this.SailiaoObj[row.sieve_source_label]
        };
      }else if(type==5){
        this.format.name.labelDisabled = false
        title = "新增配置"
        info = {
          name:"",
          desc:"",
          unit_price:"",
          sieve_source_config_id:""
        };
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
    },
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      if (this.handleType==1) {
          actionName = 'updateBatch_item';
          tipText = '筛源修改成功！';
      }else if(this.handleType==2){
        actionName = 'edit_item';
        tipText = '修改成功！';
        postData ["unit_price"]=BigNumber(postData.unit_price).multipliedBy(10000).toString()
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        postData = {"id":postData.Id};
      }else if(this.handleType==3){
        actionName = 'enable_item';
        tipText = '启用成功！';
        postData = {"id":postData.id};
      }else if(this.handleType==4){
        actionName = 'disable_item';
        tipText = '禁用成功！！';
        postData = {"id":postData.id};
      }else if(this.handleType==5){
        actionName = 'add_item';
        tipText = '添加成功！！';
        postData ["unit_price"]=BigNumber(postData.unit_price).multipliedBy(10000).toString()
      }
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0 ) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        this.onSearchGetList();
        utils.showTip(tipText);
      }else{
        utils.showSureModal({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
          "modalContent":res.data,
          "title":"提示"});
      }
      utils.hideLoading();
    },
    //删除
    sureDel(item,type) {
       this.handleType = -1;
        utils.showSureModal({
          "title":"删除提示",
          "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),
          "modalContent":"确认删除 "+item.name,"callBackArgs":{"Id":item.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          this.updateInfo(data);
        }
      });
      this.getList()
    },
     //导出列表
    async downloadFile() {
      // utils.showLoading("正在生成中")
      let new_ids=""
      if((this.selectRows.checked==true && this.selectRows.records.length!= 0)||(this.selectRows.checked==false && this.selectRows.records.length!= 0)){
        //导出值用id|id形式拼接
        this.selectRows.records.forEach(item => {
          new_ids+='|'+item.id
        });
        if(new_ids!=''){
          new_ids=new_ids.substring(1)
        }
        let res = await this.RequestPost("export_list",{"ids":new_ids});
        if(res.code==0){
          utils.hideLoading()
            await utils.sleepMs(500);
            // utils.showTip("导出成功，在IM中查收");
        }
        window.location.href = ACDN+res.data
      }else{
         utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
         "modalContent":"请至少选择一项 ",
         "title":"提示"});
      }

    },
    onChangePageSize(page,pageSize){
      this.modal = true
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(val){
      let num = new Date(val)
      let time = num.getTime()/1000;
      // this.searchData.create_at = time
    },
    onSelectChange(label,value,reset){
    },
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    unitprice(data){
      let unit_price = 0
      data.forEach(item =>{
        unit_price+=item.unit_price
      })
      return unit_price
    },
    showFooter(){
     if(this.footerMethod){
         return true;
     }else{
         return false;
     }
    }
  },
};
</script>
